import React, { useState, useEffect, useContext } from 'react'
import { Table, Spin, message } from 'antd'
import Container from '@/appComponents/Container'
import Filter from './Filter'
import ModalTable from '@/components/ModalTable'
import ModalEcharts from './ModalEcharts'
import {
  getProcessEvaluation,
  getPlanHistoryList,
  postCreateHistoryTable
} from '@/api/electricity'
import _ from 'lodash'
import { downloadExcel } from '@/commonjs/util.help.js'
import icon from '@/images/electricity/add.png'
import getColumns from './index-data'
import { EditableRow, EditableCell } from './Editable'
import { LayoutContext } from '&/pages/layouts/context'

import '../ProcessAssessment/index.scss'
const EvaluationReview = () => {
  const { activePlan } = useContext(LayoutContext)
  const [isLoading, setIsLoading] = useState(false)
  const [defaultColumns, setDefaultColumns] = useState([])
  const [dataSource, setDataSource] = useState([])
  const [upData, setUpData] = useState([])
  const [timeList, setTimeList] = useState([])
  const [historyId, setHistoryId] = useState(null)
  const [keys, setKeys] = useState([])
  const [paramsData, setParamsData] = useState({
    county_id: -1
  })
  const [historyParams, setHistoryParams] = useState(null)
  const [open, setOpen] = useState(false)
  const [record, setRecord] = useState(null)
  const [total, setTotal] = useState(null)
  const columns = defaultColumns.map((col) => {
    if (!col.editable) {
      return col
    }
    return {
      ...col,
      onCell: (record) => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave
      })
    }
  })
  const components = {
    body: {
      row: EditableRow,
      cell: EditableCell
    }
  }
  const getParams = () => {
    let newParamsData = {}
    for (let key in paramsData) {
      if (paramsData[key] != (-1 || '-1')) {
        newParamsData[key] = paramsData[key]
      }
    }
    return newParamsData
  }
  // 表格复选框配置
  const rowSelection = {
    onChange: (k, list) => {
      setKeys(k)
      if (k.length) {
        setHistoryParams(list)
      } else {
        setHistoryParams(null)
      }
    },
    selectedRowKeys: keys
  }
  // 修改表格内容
  const handleSave = (row) => {
    const newData = [...dataSource]
    const index = newData.findIndex((item) => row.ent_id === item.ent_id)
    const item = newData[index]
    newData.splice(index, 1, {
      ...item,
      ...row
    })
    setKeys([])
    setDataSource(newData)
  }
  // 查询按钮
  const onQuery = () => {
    getManualEvaluationTable()
  }
  // 请求数据评估数据
  const getManualEvaluationTable = () => {
    setKeys([])
    setHistoryParams(null)
    setIsLoading(true)
    getProcessEvaluation({
      history_id: historyId,
      second_instance: 2,
      type_id: 1,
      plan_id: activePlan.plan_id,
      ...getParams()
    }).then((res) => {
      setIsLoading(false)
      const data = res
        .map((item, k) => {
          return {
            key: k,
            is_night: '否',
            is_model: '否',
            is_implement_now: '是',
            ...item
          }
        })
        .filter((i) => i.is_update == 1) // 筛选出未评估的数据
      setUpData(data)
      setDataSource(data)
      setTotal({
        allTotal: res.length,
        okTotal: res.filter((i) => i.is_update == 0).length,
        twoTotal: data.length
      })
      setDefaultColumns(getColumns(setRecord, setOpen, paramsData, data))
    })
  }
  // 提交到历史表格
  const submitHistoryTable = (e) => {
    if (historyParams) {
      let result = timeList.find((i) => {
        return i.history_id == historyId
      })
      postCreateHistoryTable({
        data: historyParams,
        plan_id: activePlan.plan_id,
        start_time: result.start_time,
        end_time: result.end_time,
        second_instance: '2'
      }).then((res) => {
        message.info(res)
        setHistoryParams(null)
        updateHistoryList()
        getManualEvaluationTable()
      })
    } else {
      message.info('请选择要提交的数据111')
    }
  }
  // 请求时间列表
  const updateHistoryList = () => {
    getPlanHistoryList({
      plan_id: activePlan.plan_id
    }).then((data) => {
      setTimeList(data)
    })
  }
  // 导出数据
  const onDownloadExcel = () => {
    const data = historyParams || dataSource
    downloadExcel(data, defaultColumns, '数据评估')
  }
  // 筛选数据方法
  const upDateDataSource = (v) => {
    // 数据评估
    let dataSource = getUpData(v, upData, 'is_measure_voluntarily')
    setDataSource(dataSource)
  }
  // 处理筛选数据
  const getUpData = (v, data, key) => {
    if (v == 1) {
      return data
    }
    let text
    if (v == 2) {
      text = '是'
    } else {
      text = '否'
    }
    let newData = data.filter((i) => {
      return i[key] == text
    })
    return newData
  }

  useEffect(() => {
    if (!activePlan.plan_id) return
    getPlanHistoryList({
      plan_id: activePlan.plan_id
    }).then((data) => {
      setTimeList(data)
      setHistoryId(data[data.length - 1].history_id)
    })
  }, [activePlan.plan_id])

  useEffect(() => {
    if (historyId) {
      onQuery()
    } else {
      setDataSource([])
      setDefaultColumns([])
    }
  }, [historyId, paramsData])

  return (
    <Container>
      <Container.ContainerQuery title="查询条件">
        <Filter
          onQuery={onQuery}
          paramsData={paramsData}
          setParamsData={setParamsData}
          timeList={timeList}
          historyId={historyId}
          setHistoryId={setHistoryId}
          submitHistoryTable={submitHistoryTable}
          onDownloadExcel={onDownloadExcel}
        />
      </Container.ContainerQuery>
      <Container.ContainerContent>
        <Spin tip="Loading......" spinning={isLoading}>
          <div className="tips_box">
            <div>
              *注意：提交仅可提交当前分页内容，切换分页之前选择和填写的内容不会保留；
            </div>
            <div>
              当前页面共需评估<span>{total?.allTotal}</span>家企业,已评估
              <span>{total?.okTotal}</span>
              家企业,未评估
              <span>{dataSource.length}</span>家企业
            </div>
          </div>
          <Table
            rowSelection={{
              type: 'checkbox',
              columnWidth: 30,
              ...rowSelection
            }}
            components={components}
            rowClassName={() => 'editable-row'}
            columns={columns}
            dataSource={dataSource}
            bordered
            scroll={{ y: '65vh' }}
            rowKey={(record) => record.key}
            pagination={{
              defaultPageSize: 20,
              position: ['bottomCenter'],
              showQuickJumper: true,
              showTotal: () => `共 ${dataSource.length} 条`
            }}
          />
        </Spin>
        <ModalEcharts record={record} open={open} setOpen={setOpen} />
      </Container.ContainerContent>
    </Container>
  )
}
export default EvaluationReview
